/**
 * <p>Title: ServiceZMCM81.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张坤
 * @version 1.0
 * <pre>History:
 *          2010-12-17 下午01:33:45  张坤  Create
 *</pre>
 */
package com.baosight.sczx.zm.cm.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.cm.ExportApplication;
import com.baosight.sczx.common.zm.cInterface.cm.MaterialRation;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.zm.cm.domain.ZMCMExportApplicationDetail;

/**领料申请管理
 * <p>Title: ServiceZMCM81.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张坤
 * @version 1.0
 * <pre>History:
 *          2010-12-17 下午01:33:45  张坤  Create
 *</pre>
 */
public class ServiceZMCM81 extends ServiceEPBase {
	/**
	 * 初始数据管理从表页面初始化方法
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM81</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2010-12-17 下午01:35:45  张坤  Create
	 * </p>
	 *
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) 
	{
		EiInfo outInfo;
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		outInfo = this.query(inInfo);
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.units"));
		return outInfo;
	}
	
	/**
	 * 查询方法
	 * 根据查询条件查询从表数据信息
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM81</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2010-12-17 下午01:36:45  张坤  Create
	 * </p>
	 *
	 */
	@Override
	public EiInfo query(EiInfo inInfo) 
	{
		String fdApplicationId = inInfo.getString("fdApplicationId");
		StaticTools.setQueryParameters(inInfo, "fdApplicationId", fdApplicationId, true);//添加查询条件
		EiInfo outInfo = super.query(inInfo, "ZMCMExportApplicationDetail.query", new ZMCMExportApplicationDetail());
		return outInfo;
	}
	
	/**
	 * 修改方法
	 * 修改从表数据
	 * <p>Function: update</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM81</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2010-12-17 下午01:43:45  张坤  Create
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public EiInfo update(EiInfo inInfo) 
	{
		String fdApplicationId = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdApplicationId");
		inInfo.getBlock(EiConstant.resultBlock).setCell(0, "fdAuditNumber", inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdApplicationNumber"));
		if(inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdRequirePlan") == null
				||"".equals(inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdRequirePlan")))
		{
			String fdApplicationNumber = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdApplicationNumber");
			String fdPrice = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdPrice");
			Map _map = new HashMap();
			_map.put("fdApplicationSum", BigDecimal.valueOf(Double.parseDouble(fdApplicationNumber) * Double.parseDouble(fdPrice)));
			_map.put("fdApplicationId", fdApplicationId);
			dao.update("ZMCMExportApplication.applicationSum2", _map);//更新主表金额
			
			return super.update(inInfo, "ZMCMExportApplicationDetail.update");//更新从表数据
		}
		
		String fdRequirePlan = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdRequirePlan");
		Map inMap = new HashMap();
		inMap.put("fdRequirePlan", fdRequirePlan);
		List _list = dao.query("ZMCMTeammaterialplanDetail.queryApplicationExportNum", inMap);
		String fdApplicationExportedNumber = "0.0";
		if(_list.size()>0)
		{
			fdApplicationExportedNumber = ((Map)_list.get(0)).get("fdApplicationExportNum").toString();
		}
		
		String fdPurchaseNum = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdPurchaseNum");
		String fdApplicationNumber = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdApplicationNumber");
		if((Double.parseDouble(fdApplicationNumber) - Double.parseDouble(fdPurchaseNum)) > 0)
		{
			inInfo.setStatus(-1);
			inInfo.addMsg("申请数量不能大于需求数量！");
			return inInfo;
		}
		
		if((Double.parseDouble(fdApplicationNumber) - 
				(Double.parseDouble(fdPurchaseNum) - Double.parseDouble(fdApplicationExportedNumber))) > 0)
		{
			inInfo.setStatus(-1);
			inInfo.addMsg("申请数量不能大于需求数量减已申请数量！");
			return inInfo;
		}
		
		_list = updateTeamPlan(inInfo);
		
		if(_list == null)
		{
			inInfo.setStatus(-1);
			inInfo.addMsg("本次领料超出剩余月费用额度！");
			return inInfo;
		}
		
		Double double_fdApplicationSum = 0.0;
		EiInfo outInfo = new EiInfo();
		outInfo = super.update(inInfo, "ZMCMExportApplicationDetail.update");//更新从表数据
		
		for(int i=0; i<_list.size(); i++)
		{
			ZMCMExportApplicationDetail detail = (ZMCMExportApplicationDetail)_list.get(i);
			Double double_fdAuditNumber = detail.getFdAuditNumber();//获取个数
			Double double_fdPrice =  detail.getFdPrice();//获取价格
			double_fdApplicationSum = double_fdApplicationSum + double_fdAuditNumber * double_fdPrice;
		}
		
		inMap = new HashMap();
		inMap.put("fdApplicationSum", BigDecimal.valueOf(double_fdApplicationSum));
		inMap.put("fdApplicationId", fdApplicationId);
		dao.update("ZMCMExportApplication.applicationSum1", inMap);//更新主表金额

		return outInfo;
	}
	
	private Double countmonthRation(EiInfo inInfo)
	{
		Map<String, String> params = new HashMap<String, String>();

		params.put("fdYear", inInfo.getBlock("result").getCell(0, "fdYear").toString());
		params.put("fdMonth", inInfo.getBlock("result").getCell(0, "fdMonth").toString());	
		params.put("orgCode", inInfo.getBlock("result").getCell(0, "fdApplicationDepartment").toString());	
		params.put("fdApplicationDepartment", inInfo.getBlock("result").getCell(0, "fdApplicationDepartment").toString());	
		
		List<Map> result = MaterialRation.getMaterialRation("ZMCMMaterialRation.lessMoney", params);
		Double monthRation = new Double(0);
		if(result.size()>0)
		{
			monthRation = Double.valueOf(result.get(0).get("monthRation").toString());
		}

		List<Map> result1 = ExportApplication.getSUM("ZMCMExportApplication.allMoney", params);
		Double sum= new Double(0);
		if(result1.size()>0)
		{
			if(result1.get(0).get("sum") != null)
			{
				sum = Double.valueOf(result1.get(0).get("sum").toString());
			}
		}
		return (monthRation - sum);		
	}
	
	/**
	 * 
	 * <p>Function: updateTeamPlan</p>
	 * <p>Description: </p>
	 * <p>return value:List</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:23:53 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private List updateTeamPlan(EiInfo inInfo)
	{
		Double monthRation = countmonthRation(inInfo);
		Double money = 0.0;
		String fdKeyId = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdKeyId");
		String fdApplicationId = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdApplicationId");
		Map inMap = new HashMap();
		inMap.put("fdKeyId", fdKeyId);
		inMap.put("fdApplicationId", fdApplicationId);
		List _list = dao.query("ZMCMExportApplicationDetail.queryStrict", inMap);
		
		for(int i=0; i<_list.size(); i++)
		{
			ZMCMExportApplicationDetail md = (ZMCMExportApplicationDetail)_list.get(i);
			
			if(fdKeyId.equals(md.getFdKeyId()))
			{
				String fdApplicationNumber = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdApplicationNumber");
				
				money += Double.parseDouble(fdApplicationNumber)*md.getFdPrice();
				
				if(money > monthRation)
				{
					return null;
				}
				inMap = new HashMap();
				inMap.put("fdApplicationNumber", 0-md.getFdApplicationNumber()+Double.parseDouble(fdApplicationNumber));
				inMap.put("fdRequirePlan", md.getFdRequirePlan());
				
				dao.update("ZMCMTeammaterialplanDetail.updatefdApplicationExportNumForNoCode", inMap);
				
				if(md.getFdApplicationNumber()>md.getFdAuditNumber())
				{
					inMap.put("fdStatus", "部分领用");
					dao.update("ZMCMTeammaterialplanDetail.updatefdStatusForNoCode", inMap);
				}
				break;
			}
		}
		
		return _list;
	}
	
	/**
	 * 
	 * <p>Function: delete</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM81</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:24:04 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo delete(EiInfo inInfo)
	{
		String fdApplicationId = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdApplicationId");
		updateTeamPlanForDelete(inInfo);
		
		EiInfo tmp = super.delete(inInfo, "ZMCMExportApplicationDetail.delete");//删除从表数据
		
		Map inMap = new HashMap();
		inMap.put("fdApplicationId", fdApplicationId);
		List _list = dao.query("ZMCMExportApplicationDetail.queryStrict", inMap);
		
		Double double_fdApplicationSum = 0.0;
		for(int i=0; i<_list.size(); i++)
		{
			ZMCMExportApplicationDetail detail = (ZMCMExportApplicationDetail)_list.get(i);
			Double double_fdAuditNumber = detail.getFdAuditNumber();//获取个数
			Double double_fdPrice =  detail.getFdPrice();//获取价格
			double_fdApplicationSum = double_fdApplicationSum + double_fdAuditNumber * double_fdPrice;
		}
		
		inMap = new HashMap();
		inMap.put("fdApplicationSum", BigDecimal.valueOf(double_fdApplicationSum));
		inMap.put("fdApplicationId", fdApplicationId);
		dao.update("ZMCMExportApplication.applicationSum", inMap);//更新主表金额

		EiInfo outInfo = this.query(inInfo);
        outInfo.setMsg(tmp.getMsg());
        outInfo.setDetailMsg(tmp.getDetailMsg());
		return outInfo;
	}
	
	/**
	 * 
	 * <p>Function: updateTeamPlanForDelete</p>
	 * <p>Description: </p>
	 * <p>return value:void</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:24:15 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void updateTeamPlanForDelete(EiInfo inInfo)
	{
		LinkedList idList = new LinkedList();
		for(int i=0; i<inInfo.getBlock(EiConstant.resultBlock).getRowCount(); i++)
		{
			idList.add(inInfo.getBlock(EiConstant.resultBlock).getCellStr(i, "fdKeyId"));
		}
		
		String fdApplicationId = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdApplicationId");
		Map inMap = new HashMap();
		inMap.put("fdApplicationId", fdApplicationId);
		List _list = dao.query("ZMCMExportApplicationDetail.queryStrict", inMap);
		
		for(int i=0; i<_list.size(); i++)
		{
			ZMCMExportApplicationDetail md = (ZMCMExportApplicationDetail)_list.get(i);
			
			if(idList.contains(md.getFdKeyId()))
			{
				inMap = new HashMap();
				inMap.put("fdApplicationNumber", 0-md.getFdApplicationNumber());
				inMap.put("fdRequirePlan", md.getFdRequirePlan());
						
				dao.update("ZMCMTeammaterialplanDetail.updatefdApplicationExportNumForNoCode", inMap);
				inMap.put("fdStatus", "部分领用");
				dao.update("ZMCMTeammaterialplanDetail.updatefdStatusForNoCode", inMap);
			}
		}
	}
	
	/**
	 * 新增方法
	 * 新增从表数据
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM81</p>s
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-06-23 下午01:38:45  张坤  Create
	 * </p>
	 *
	 */
	@Override
	public EiInfo insert(EiInfo inInfo) 
	{
		EiInfo outInfo = new EiInfo();
		EiInfo outInfo_up = null;
		Double fdApplicationSum = 0.0;
		boolean validateStatus = validateNum(inInfo);
		if(validateStatus)
		{
			return inInfo;
		}
		else
		{
			outInfo_up = super.update(inInfo, "ZMCMTeammaterialplanDetail.updatefdStatusForNoCode");
			if(outInfo_up.getStatus() == -1)
			{
				outInfo.setStatus(-1);
				outInfo.setMsg(outInfo_up.getMsg());
				return outInfo;
			}
			
			String exportApplicationKeyId = inInfo.getBlock("inqu_status").getCellStr(0, "fdApplicationId");//主表主键
			for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
			{
				inInfo.getBlock("result").setCell(i, "fdKeyId", TablePk.getInstance().getNextValue("T_CM_EXPORT_APPLICATION_DETAIL"));//从表主键
				inInfo.getBlock("result").setCell(i, "fdApplicationId", exportApplicationKeyId);
				
				Map inMap = new HashMap();
				inMap.put("fdApplicationId", inInfo.getBlock("result").getCellStr(i, "fdApplicationId"));
				inMap.put("fdMaterialCode", inInfo.getBlock("result").getCellStr(i, "fdMaterialCode"));
				inMap.put("fdMaterialName", inInfo.getBlock("result").getCellStr(i, "fdMaterialName"));
				List _list = dao.query("ZMCMExportApplicationDetail.countSameMaterial", inMap);
				if(Integer.parseInt(((Map)_list.get(0)).get("cnt").toString()) > 0)
				{
					outInfo.setStatus(-1);
					outInfo.setMsg("已有物资["+inInfo.getBlock("result").getCellStr(i, "fdMaterialName")+"]的申请，不能再次新增！");
					return outInfo;
				}
				Double sum = 0.0;
				Double fdApplicationNumber =  Double.valueOf(inInfo.getBlock("result").getCell(i, "fdApplicationNumber").toString());//获取申请数量
				inInfo.getBlock("result").setCell(i, "fdAuditNumber", fdApplicationNumber);//将申请数量一并赋给审批数量
				Double fdPrice =new Double(0);
				if(inInfo.getBlock("result").getCell(i, "fdPrice") != null)
				{
					fdPrice=  Double.valueOf(inInfo.getBlock("result").getCell(i, "fdPrice").toString());//获取价格
				}
				
				sum = fdApplicationNumber * fdPrice;
				fdApplicationSum = fdApplicationSum + sum;
				inInfo.getBlock("result").setCell(i, "fdApplicationSum", fdApplicationSum);
				inInfo.getBlock(EiConstant.resultBlock).setCell(i, "fdStatus", "部分");
			}

			outInfo = super.insert(inInfo, "ZMCMExportApplicationDetail.insert", "result");//插入从表数据
			
			if(outInfo.getStatus() == -1)
			{
				return outInfo;
			}
			
			outInfo_up = super.update(inInfo, "ZMCMTeammaterialplanDetail.updatefdApplicationExportNumForNoCode");// 更新已申请领用数量
			if(outInfo_up.getStatus() == -1)
			{
				outInfo.setStatus(-1);
				outInfo.setMsg(outInfo_up.getMsg());
				return outInfo;
			}
			
			outInfo_up = super.update(inInfo, "ZMCMExportApplication.applicationSum1");//更新主表金额
			if(outInfo_up.getStatus() == -1)
			{
				outInfo.setStatus(-1);
				outInfo.setMsg(outInfo_up.getMsg());
				return outInfo;
			}

			return outInfo;
		}
	}
	
	/**
	 * 校验输入值
	 * <p>Function: validate</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-06-23 下午01:33:45  张坤  Create
	 * </p>
	 *
	 */
	private boolean validateNum(EiInfo inInfo) {
		//剩余额度
		Double Money =  Double.valueOf(inInfo.get("Money").toString());
		//申请金额
		Double applicationMoney = new Double(0);
		
		for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
		{
			Object fdAN = inInfo.getBlock("result").getCell(i,"fdApplicationNumber");
			Double fdApplicationNumber    = (fdAN == null)? new Double(0):Double.valueOf(fdAN.toString());
            //申请数量
			Object fdEN = inInfo.getBlock("result").getCell(i,"fdExportedNumber");
            Double fdExportedNumber       = (fdEN == null)? new Double(0):Double.valueOf(fdEN.toString());
            //已发数量
            Object fdPN = inInfo.getBlock("result").getCell(i,"fdPurchaseNum");
            Double fdPurchaseNum          = (fdPN == null)? new Double(0):Double.valueOf(fdPN.toString());
            //需求数量
            Object fdAE = inInfo.getBlock("result").getCell(i,"fdApplicationExportNum");
            Double fdApplicationExportNum = (fdAE == null)? new Double(0):Double.valueOf(fdAE.toString());
            //已申请领用数量
            
            Object fdPE = inInfo.getBlock("result").getCell(i,"fdPrice");
            Double fdPrice = (fdAE == null)? new Double(0):Double.valueOf(fdPE.toString());
            
            //Object fdAP = inInfo.getBlock("result").getCell(i,"fdApplicationSum");
            //Double fdApplicationSum = (fdAP == null)? new Double(0):Double.valueOf(fdAP.toString());

            //申请金额 
            applicationMoney = applicationMoney + fdApplicationNumber*fdPrice;
        	BigDecimal data1 = new BigDecimal(fdApplicationNumber);
        	BigDecimal data2 = new BigDecimal(fdPurchaseNum - fdApplicationExportNum);
        	BigDecimal data3 = new BigDecimal(fdPurchaseNum - fdExportedNumber);
            if (data1.compareTo(data2) > 0)
	        	{
	        		inInfo.setStatus(-1);
					inInfo.setMsg("申请数量不允许大于需求数量减去已申请数量！");
					return true;
	        	}
            if (data1.compareTo(data3) > 0)
            	{
            		inInfo.setStatus(-1);
					inInfo.setMsg("申请数量不允许大于需求数量减去已发数量！");
					return true;
            	}
        	if(data1.compareTo(data3) < 0)
	        	{
	        		inInfo.getBlock("result").setCell(i, "fdStatus", "部分领用");
	        	}


        	if(data1.compareTo(data2)==0)
        	{
        		inInfo.getBlock("result").setCell(i, "fdStatus", "全部领用");
        	}

		}
		if(applicationMoney > Money)
		{
			inInfo.setStatus(-1);
			inInfo.setMsg("本次申请的金额已超过本单位本月剩余申请额度，重新填写领料申请明细或联系相关人员提高本月费用额度！");
			return true;
		}
		
		return false;
	}
	
	/**
	 * 根据出库修改状态
	 * <p>Function: updateForStatusToPart</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-15上午09:33:15 余虎
	 * </p>
	 *
	 */
	public EiInfo updateForStatus(EiInfo inInfo) {
		  EiInfo outInfo = super.update(inInfo, "ZMCMExportApplicationDetail.updateForStatus"); 
	      return outInfo;
	        
	}	
}
